# @Time : 2022/12/14 11:02
from flask import Flask,request,jsonify,Blueprint,session
import json
import string
from datetime import datetime
import config
from exts import db
article_bp = Blueprint("article",__name__,url_prefix='/article')


app = Flask(__name__)

@article_bp.route('/showInfo',methods=['GET','POST'])
def showArticle():
    engine = db.get_engine()
    data = json.loads(request.data)
    articleID = data.get('article_id')
    type = data.get('type')
    if type == 'article':
        with engine.connect() as conn:
            try:
                cursor   = conn.execute(f"select * from article where article_id = {articleID}")
                item = cursor.fetchone();
                return {
                    'account': item[1],
                    'content': item[2],
                    'postTime': item[3],
                    'agreeNum': item[4],
                    'title':    item[5]
                    }
            except:
                return {'content': 'Can not found article content!'}

    elif type == 'getCom':
        with engine.connect() as conn:
            try:
                cursor = conn.execute(f"select * from reply where article_id = {articleID} order by replyTime asc;")
                replyData = cursor.fetchall();

                replyInfo = []  #记录该文章的所有评论信息

                for item in replyData:
                    if item[3] is None:     #如果replyID为空，返回回复文章的楼主评论
                        floor={
                            'id':item[0],
                            'accountname':item[1],
                            'content':item[2],
                            'replyTime':item[5],
                            'replyToFloor':[],
                            'replyType':'reply_to_article'
                        }
                        replyInfo.append(floor)
                    else:
                        replyFloor = {
                            'id': item[0],
                            'accountname': item[1],
                            'content': item[2],
                            'replyTime': item[5],
                            'replyType': 'reply_to_customer'
                        }
                        # 将回复楼主的评论添加进每一楼的字典中
                        for j in replyInfo:
                            #找到该评论属于哪一楼
                            if item[3] == j[id]:
                                j['replyToFloor'].append(replyFloor)
                return replyInfo

            except:
                return {'content': 'Can not found article content!'}


@article_bp.route('/modifyArticle',methods=['GET','POST'])
def modifyArticle():
    engine = db.get_engine()
    data = json.loads(request.data)
    articleID = data.get('article_id')
    newContent = data.get('newContent')
    with engine.connect() as conn:
        try:
            conn.execute(f"update article set content = {newContent} where article_id = {articleID};")
            conn.execute(f"update article set posttime = {datetime.now()} where article_id = {articleID};")
        except:
            return 'ERROR'

    return 'ok'


@article_bp.route('/modifyArticle',methods=['GET','POST'])
def modifyArticle():
    engine = db.get_engine()
    data = json.loads(request.data)
    articleID = data.get('article_id')
    newContent = data.get('newContent')
    with engine.connect() as conn:
        try:
            conn.execute(f"update article set content = {newContent} where article_id = {articleID};")
            conn.execute(f"update article set posttime = {datetime.now()} where article_id = {articleID};")
        except:
            return 'ERROR'

    return 'ok'